Bashir Magomedov
Bashir Magomedov

Reputation: 2891

ASP .NET 4 Wev Api controller - modify response type

Let’s say I’ve got a simple Web API controller. I want to return a basic .NET type as a result. For example:

public class LoginController : ApiController
{
    [HttpPost]
    public bool Authenticate(LoginUserViewModel loginUserViewModel)
    {
        return true;
    }
}

I’m getting different results in different browsers even if the request is exactly the same for all of them. In Chrome and IE7 I get Content-Type in Response Headers as application/json; charset=utf-8, and response value equal to "true". Firefox recognizes response Content-Type as application/xml; charset=utf-8 and sets response value to:

"<boolean xmlns="http://schemas.microsoft.com/2003/10/Serialization/">true</boolean>"

Is there any way to set response type on the server-side so it is always the same? Thanks.

UPDATE: Here is JavaScript that I use to call my controller.

                    Ext.Ajax.request({
                    async: false,
                    url: 'Login/Authenticate',
                    defaultHeaders: { 'Accept': 'application/json' },
                    jsonData: user,
                    success: function (response, options) {
                        if (response.responseText !== 'true') {
                            Ext.Msg.alert('Error', 'Login failed, please try again');
                        } else {
                            document.location = 'Main.aspx';
                        }
                    },
                    failure: function (response, options) {
                        Ext.MessageBox.hide();
                        Ext.Msg.alert('Error', 'Server error. Cannot authenticate user.');
                    }
                });

Upvotes: 0

Views: 1396

Answers (1)

Darrel Miller
Darrel Miller

Reputation: 142252

This is because browsers send different Accept headers. Web API uses the accept header to determine the content-type of the response. By default Web API loads up a few different formatters into it's configuration.Formatters collection.

One way to force the response of to be a specific media-type is to remove all the existing formatters and add only the one you want.

configuration.Formatters.Clear();
configuration.Formatters.Add(new JsonMediaTypeFormatter());

Upvotes: 1

Related Questions