Rectangle 27 15

It's possible that your WCF service is returning HTML. In this case, you'll want to set up a binding on the service side to return XML instead. However, this is unlikely: if it is the case, let me know and I'll make an edit with more details.

The more likely reason is that your service is throwing an error, which is returning an HTML error page. You can take a look at this blog post if you want details.

tl;dr: There are a few possible configurations for error pages. If you're hosting on IIS, you'll want to remove the <httpErrors> section from the WCF service's web.config file. If not, please provide details of your service hosting scenario and I can come up with an edit to match them.

Having seen your edit, you can see the full error being returned. Apache can't tell which service you want to call, and is throwing an error for that reason. The service will work fine once you have the correct endpoint - you're pointed at the wrong location. I unfortunately can't tell from the information available what the right location is, but either your action (currently null!) or the URL is incorrect.

The WEb service is a customers I don't have access to this, other than the url I am given to consume

Hi, just edited my response having seen the stack trace you put in. Looks like you need to change your endpoint address.

Hi, I checked with fiddler the app is sending the same url, albeit without the ?wsdl on the end. I can post the code for the project if it helps

?wsdl is important - it means the browser is just getting "Web Services Description Language" for the service, and not calling the service. The WSDL, if you learn to read it, will tell you the action to send. Add that action to your client's endpoint address, and you should have more luck with the service.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

c# - The content type application/xml;charset=utf-8 of the response me...

c# wcf wcf-binding
Rectangle 27 15

It's possible that your WCF service is returning HTML. In this case, you'll want to set up a binding on the service side to return XML instead. However, this is unlikely: if it is the case, let me know and I'll make an edit with more details.

The more likely reason is that your service is throwing an error, which is returning an HTML error page. You can take a look at this blog post if you want details.

tl;dr: There are a few possible configurations for error pages. If you're hosting on IIS, you'll want to remove the <httpErrors> section from the WCF service's web.config file. If not, please provide details of your service hosting scenario and I can come up with an edit to match them.

Having seen your edit, you can see the full error being returned. Apache can't tell which service you want to call, and is throwing an error for that reason. The service will work fine once you have the correct endpoint - you're pointed at the wrong location. I unfortunately can't tell from the information available what the right location is, but either your action (currently null!) or the URL is incorrect.

The WEb service is a customers I don't have access to this, other than the url I am given to consume

Hi, just edited my response having seen the stack trace you put in. Looks like you need to change your endpoint address.

Hi, I checked with fiddler the app is sending the same url, albeit without the ?wsdl on the end. I can post the code for the project if it helps

?wsdl is important - it means the browser is just getting "Web Services Description Language" for the service, and not calling the service. The WSDL, if you learn to read it, will tell you the action to send. Add that action to your client's endpoint address, and you should have more luck with the service.

c# - The content type application/xml;charset=utf-8 of the response me...

c# wcf wcf-binding
Rectangle 27 34

First thing to understand is that the RequestMapping#produces() element in

@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")

Then, given that your method has a return type of String and is annotated with @ResponseBody, the return value will be handled by StringHttpMessageConverter which sets the Content-type header to text/plain. If you want to return a JSON string yourself and set the header to application/json, use a return type of ResponseEntity (get rid of @ResponseBody) and add appropriate headers to it.

@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> bar() {
    final HttpHeaders httpHeaders= new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>("{\"test\": \"jsonResponseExample\"}", httpHeaders, HttpStatus.OK);
}

Note that you should probably have

<mvc:annotation-driven />

in your servlet context configuration to set up your MVC configuration with the most suitable defaults.

Jackson library works perfectly fine with @ResponseBody

@user3360241 Jackson with @ResponseBody is implemented with a MappingJackson2HttpMessageConverter. It's registered after a StringHttpMessageConverter and therefore plays no part in the handling of this request.

Hm: mkyong.com/spring-mvc/spring-3-mvc-and-json-example, also that is just example. I would say that the op would like to return custom objects as Json too.

@user3360241 They might want to, but right now they are returning a String. If they did return a POJO, and assuming their config is correct, then Jackson would be involved. In this case, it isn't.

This answer is correct if you wish to return Strings to your browsers as content json, as you have indicated in your question. If you should return POJOs represented as Json, then you should use some mapper, such as the Jackson.

java - Spring MVC 4: "application/json" Content Type is not being set ...

java json spring spring-mvc content-type
Rectangle 27 104

Use ResponseEntity instead of ResponseBody. This way you have access to the response headers and you can set the appropiate content type. According to the Spring docs:

The HttpEntity is similar to @RequestBody and @ResponseBody. Besides getting access to the request and response body, HttpEntity (and the response-specific subclass ResponseEntity) also allows access to the request and response headers

@RequestMapping(method=RequestMethod.GET, value="/fooBar")
public ResponseEntity<String> fooBar2() {
    String json = "jsonResponse";
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}

hi, I want to return a serialized object but using your method I have a problem, it doesn't compile because it says: HttpHeaders is abstract can not be instantiated.... can you explain me as well how you woud do this having to return the serialization of an object? now it works fine if not using ResponseEntity

Just wanted to point out that Spring MVC 3.1 allows you to specify a value for "produces" in the RequestMapping. So you can still use @ResponseBody, but you need @RequestMapping(method=RequestMethod.GET, value="/fooBar", produces="application/json").

With this approach you can have the same method return different content-types, something that you cannot do with Spring's "produces". Also, this is the least intrusive i.e. you don't have to create/ instantiate your own MessageConverters.

java - In Spring MVC, how can I set the mime type header when using @R...

java json spring spring-mvc controller
Rectangle 27 103

Use ResponseEntity instead of ResponseBody. This way you have access to the response headers and you can set the appropiate content type. According to the Spring docs:

The HttpEntity is similar to @RequestBody and @ResponseBody. Besides getting access to the request and response body, HttpEntity (and the response-specific subclass ResponseEntity) also allows access to the request and response headers

@RequestMapping(method=RequestMethod.GET, value="/fooBar")
public ResponseEntity<String> fooBar2() {
    String json = "jsonResponse";
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}

hi, I want to return a serialized object but using your method I have a problem, it doesn't compile because it says: HttpHeaders is abstract can not be instantiated.... can you explain me as well how you woud do this having to return the serialization of an object? now it works fine if not using ResponseEntity

Just wanted to point out that Spring MVC 3.1 allows you to specify a value for "produces" in the RequestMapping. So you can still use @ResponseBody, but you need @RequestMapping(method=RequestMethod.GET, value="/fooBar", produces="application/json").

With this approach you can have the same method return different content-types, something that you cannot do with Spring's "produces". Also, this is the least intrusive i.e. you don't have to create/ instantiate your own MessageConverters.

java - In Spring MVC, how can I set the mime type header when using @R...

java json spring spring-mvc controller
Rectangle 27 3

I would just create a quick wrapper for the ajax method.

$.myAjax = function(url,data){
    return $.ajax({
        contentType: "application/json",
        url: url,
        data: data || {},
        type: "GET",
        dataType: "json"
    });
}
// used with
$.myAjax("foobar.asp").done(function(data){
    console.log(data);
}).fail(function(){
    console.log(arguments);
});

The reason that the header isn't getting passed is that if the contentType isn't specified for the given request and there is no data, the contentType is not set. It may be a bug since the contentType was set in the ajaxSetup, but I'm not positive on that.

jquery - $.ajaxSetup does not set content type for Get requests - Stac...

jquery asp.net ajax content-type pagemethods
Rectangle 27 3

I would just create a quick wrapper for the ajax method.

$.myAjax = function(url,data){
    return $.ajax({
        contentType: "application/json",
        url: url,
        data: data || {},
        type: "GET",
        dataType: "json"
    });
}
// used with
$.myAjax("foobar.asp").done(function(data){
    console.log(data);
}).fail(function(){
    console.log(arguments);
});

The reason that the header isn't getting passed is that if the contentType isn't specified for the given request and there is no data, the contentType is not set. It may be a bug since the contentType was set in the ajaxSetup, but I'm not positive on that.

jquery - $.ajaxSetup does not set content type for Get requests - Stac...

jquery asp.net ajax content-type pagemethods
Rectangle 27 17

Use the make_response method to get a response with your data. Then set the mimetype attribute. Finally return this response:

@app.route('/ajax_ddl')
def ajax_ddl():
    xml = 'foo'
    resp = app.make_response(xml)
    resp.mimetype = "text/xml"
    return resp

If you use Response directly, you lose the chance to customize the responses by setting app.response_class. The make_response method uses the app.responses_class to make the response object. In this you can create your own class, add make your application uses it globally:

class MyResponse(app.response_class):
    def __init__(self, *args, **kwargs):
        super(MyResponse, self).__init__(*args, **kwargs)
        self.set_cookie("last-visit", time.ctime())

app.response_class = MyResponse
make_response
Response

Python Flask, how to set content type - Stack Overflow

python flask
Rectangle 27 17

Use the make_response method to get a response with your data. Then set the mimetype attribute. Finally return this response:

@app.route('/ajax_ddl')
def ajax_ddl():
    xml = 'foo'
    resp = app.make_response(xml)
    resp.mimetype = "text/xml"
    return resp

If you use Response directly, you lose the chance to customize the responses by setting app.response_class. The make_response method uses the app.responses_class to make the response object. In this you can create your own class, add make your application uses it globally:

class MyResponse(app.response_class):
    def __init__(self, *args, **kwargs):
        super(MyResponse, self).__init__(*args, **kwargs)
        self.set_cookie("last-visit", time.ctime())

app.response_class = MyResponse
make_response
Response

Python Flask, how to set content type - Stack Overflow

python flask
Rectangle 27 15

It's possible that your WCF service is returning HTML. In this case, you'll want to set up a binding on the service side to return XML instead. However, this is unlikely: if it is the case, let me know and I'll make an edit with more details.

The more likely reason is that your service is throwing an error, which is returning an HTML error page. You can take a look at this blog post if you want details.

tl;dr: There are a few possible configurations for error pages. If you're hosting on IIS, you'll want to remove the <httpErrors> section from the WCF service's web.config file. If not, please provide details of your service hosting scenario and I can come up with an edit to match them.

Having seen your edit, you can see the full error being returned. Apache can't tell which service you want to call, and is throwing an error for that reason. The service will work fine once you have the correct endpoint - you're pointed at the wrong location. I unfortunately can't tell from the information available what the right location is, but either your action (currently null!) or the URL is incorrect.

The WEb service is a customers I don't have access to this, other than the url I am given to consume

Hi, just edited my response having seen the stack trace you put in. Looks like you need to change your endpoint address.

Hi, I checked with fiddler the app is sending the same url, albeit without the ?wsdl on the end. I can post the code for the project if it helps

?wsdl is important - it means the browser is just getting "Web Services Description Language" for the service, and not calling the service. The WSDL, if you learn to read it, will tell you the action to send. Add that action to your client's endpoint address, and you should have more luck with the service.

c# - The content type application/xml;charset=utf-8 of the response me...

c# wcf wcf-binding
Rectangle 27 2

Currently you are only returning a byte[] which doesn't hold much information, only the actual content (as a byte[]).

You can wrap the byte[] in a HttpEntity or ResponseEntity and set the appropriate content type on that. Spring MVC will use the content type of the entity to set the actual content type to the response.

FileTypeMap
javax.activation
@RequestMapping(value = "content/{contentId}")
@ResponseBody
public HttpEntity index(@PathVariable String contentId) {
    String filepath = // get path to file somehow
    String contentType = FileTypeMap.getDefaultFileTypeMap().getContentType(filePath);
    byte[] content = contentService.getResource(contentId);
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf(mimeType));
    return new HttpEntity(content, headers);
}

java - Spring MVC - setting the content type of a byte[] @ResponseBody...

java spring spring-mvc web-applications
Rectangle 27 1

@Get
public Representation represent() {
    StringRepresentation sr = new StringRepresentation("xml string..");
    sr.setMediaType(MediaType.APPLICATION_XML);
    return sr;
}

java - Set Content/Media type - Restlet - Stack Overflow

java content-type restlet
Rectangle 27 7

Just use the overload of Json(...) to set the correct content type.

public class HelloController
{
    public ActionResult Index()
    {
        return View()
    }

    public ActionResult Hello()
    {
        return Json(new{ greeting = "hello, world!" }, "text/html", JsonRequestBehavior.AllowGet);
    }
}

I'd rather keep the content type as application/json so that the url can be used for purposes other than this particular use case

asp.net mvc - calling @Html.Action for JsonResult changes my response ...

asp.net-mvc content-type jsonresult
Rectangle 27 4

You should bypass the content negotiation which means that you should return a new instance of HttpResponseMessage directly and set the content and the content type yourself:

return new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent(".hiddenView { display: none; }", Encoding.UTF8, "text/css")
    };

Just to say I think it is worth using the overload for StringContent to specify the content type as CSS StringContent(css, Encoding.UTF8, "text/css")

@MarkJones, great idea (otherwise it would server text/plain which is OK but better to use text/css as you said). I've edited the answer accordingly.

ASP.Net WebAPI Return CSS - Stack Overflow

asp.net-web-api
Rectangle 27 3

As the error said - you need a WebContentTypeMapper to "tell" WCF to read the incoming XML messages as raw messages. You'd set the mapper in your binding. For example, the code below shows how you could define such a binding.

public class MyMapper : WebContentTypeMapper
{
    public override WebContentFormat GetMessageFormatForContentType(string contentType)
    {
        return WebContentFormat.Raw; // always
    }
}
static Binding GetBinding()
{
    CustomBinding result = new CustomBinding(new WebHttpBinding());
    WebMessageEncodingBindingElement webMEBE = result.Elements.Find<WebMessageEncodingBindingElement>();
    webMEBE.ContentTypeMapper = new MyMapper();
    return result;
}

c# - WCF Post Request content type text/xml - Stack Overflow

c# wcf post content-type
Rectangle 27 419

Try using a simple HttpResponseMessage with its Content property set to a StreamContent:

// using System.IO;
// using System.Net.Http;
// using System.Net.Http.Headers;

public HttpResponseMessage Post(string version, string environment,
    string filetype)
{
    var path = @"C:\Temp\test.exe";
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = 
        new MediaTypeHeaderValue("application/octet-stream");
    return result;
}

A few things to note about the stream used:

Would you happen to know when the stream gets closed? I am assuming the framework ultimately calls HttpResponseMessage.Dispose(), which in turn calls HttpResponseMessage.Content.Dispose() effectively closing the stream.

Steve - you're correct and I verified by adding a breakpoint to FileStream.Dispose and running this code. The framework calls HttpResponseMessage.Dispose, which calls StreamContent.Dispose, which calls FileStream.Dispose.

You can't really add a using to either the result (HttpResponseMessage) or the stream itself, since they'll still be used outside the method. As @Dan mentioned, they're disposed by the framework after it's done sending the response to the client.

@B.ClayShannon yes, that's about it. As far as the client is concerned it's just a bunch of bytes in the content of the HTTP response. The client can do with those bytes whatever they choose, including saving it to a local file.

@carlosfigueira, hi, do you know how to delete the file after the bytes are all sent?

Returning binary file from controller in ASP.NET Web API - Stack Overf...

asp.net asp.net-mvc asp.net-web-api
Rectangle 27 410

Try using a simple HttpResponseMessage with its Content property set to a StreamContent:

// using System.IO;
// using System.Net.Http;
// using System.Net.Http.Headers;

public HttpResponseMessage Post(string version, string environment,
    string filetype)
{
    var path = @"C:\Temp\test.exe";
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = 
        new MediaTypeHeaderValue("application/octet-stream");
    return result;
}

A few things to note about the stream used:

Would you happen to know when the stream gets closed? I am assuming the framework ultimately calls HttpResponseMessage.Dispose(), which in turn calls HttpResponseMessage.Content.Dispose() effectively closing the stream.

Steve - you're correct and I verified by adding a breakpoint to FileStream.Dispose and running this code. The framework calls HttpResponseMessage.Dispose, which calls StreamContent.Dispose, which calls FileStream.Dispose.

You can't really add a using to either the result (HttpResponseMessage) or the stream itself, since they'll still be used outside the method. As @Dan mentioned, they're disposed by the framework after it's done sending the response to the client.

@B.ClayShannon yes, that's about it. As far as the client is concerned it's just a bunch of bytes in the content of the HTTP response. The client can do with those bytes whatever they choose, including saving it to a local file.

@carlosfigueira, hi, do you know how to delete the file after the bytes are all sent?

Returning binary file from controller in ASP.NET Web API - Stack Overf...

asp.net asp.net-mvc asp.net-web-api
Rectangle 27 408

Try using a simple HttpResponseMessage with its Content property set to a StreamContent:

// using System.IO;
// using System.Net.Http;
// using System.Net.Http.Headers;

public HttpResponseMessage Post(string version, string environment,
    string filetype)
{
    var path = @"C:\Temp\test.exe";
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = 
        new MediaTypeHeaderValue("application/octet-stream");
    return result;
}

A few things to note about the stream used:

Would you happen to know when the stream gets closed? I am assuming the framework ultimately calls HttpResponseMessage.Dispose(), which in turn calls HttpResponseMessage.Content.Dispose() effectively closing the stream.

Steve - you're correct and I verified by adding a breakpoint to FileStream.Dispose and running this code. The framework calls HttpResponseMessage.Dispose, which calls StreamContent.Dispose, which calls FileStream.Dispose.

You can't really add a using to either the result (HttpResponseMessage) or the stream itself, since they'll still be used outside the method. As @Dan mentioned, they're disposed by the framework after it's done sending the response to the client.

@B.ClayShannon yes, that's about it. As far as the client is concerned it's just a bunch of bytes in the content of the HTTP response. The client can do with those bytes whatever they choose, including saving it to a local file.

@carlosfigueira, hi, do you know how to delete the file after the bytes are all sent?

Returning binary file from controller in ASP.NET Web API - Stack Overf...

asp.net asp.net-mvc asp.net-web-api
Rectangle 27 11

Expanding on the answer from https://stackoverflow.com/users/183056/sami-beyoglu, if you set the Content type, then jQuery will be able to convert the returned data into an object for you.

public ActionResult DoSomething()
{
    dynamic cResponse = new ExpandoObject();
    cResponse.Property1 = "value1";
    cResponse.Property2 = "value2";
    return Content(JsonConvert.SerializeObject(cResponse), "application/json");
}

Thank you, I have a hybrid mix and this is the only thing that would work for me.

JObject jo = GetJSON();                  return Content(jo.ToString(), "application/json");

Simple and Awesome.

Using JSON.NET as the default JSON serializer in ASP.NET MVC 3 - is it...

asp.net-mvc-3 json.net jsonresult
Rectangle 27 11

Expanding on the answer from https://stackoverflow.com/users/183056/sami-beyoglu, if you set the Content type, then jQuery will be able to convert the returned data into an object for you.

public ActionResult DoSomething()
{
    dynamic cResponse = new ExpandoObject();
    cResponse.Property1 = "value1";
    cResponse.Property2 = "value2";
    return Content(JsonConvert.SerializeObject(cResponse), "application/json");
}

Thank you, I have a hybrid mix and this is the only thing that would work for me.

JObject jo = GetJSON();                  return Content(jo.ToString(), "application/json");

Simple and Awesome.

Using JSON.NET as the default JSON serializer in ASP.NET MVC 3 - is it...

asp.net-mvc-3 json.net jsonresult