简体   繁体   English

使用 web api 控制器 MVC 返回 JSON

[英]Returning JSON with web api controller MVC

I am trying to convert a regular old controller I was using to an API controller and am having a little bit of difficulty.我正在尝试将我正在使用的常规旧控制器转换为 API 控制器并且遇到了一些困难。 What these series of functions do is, in the jQuery, it iterates over a file containing all the usernames of employees and for each username it makes a call to the PopulateEmployee method in my webapi controller which should return JSON and then populate a results div.这一系列函数的作用是,在 jQuery 中,它遍历包含员工所有用户名的文件,并且对于每个用户名,它调用我的 webapi 控制器中的 PopulateEmployee 方法,该方法应该返回 JSON,然后填充结果 div。

When manually navigating to ..domain../staffinformation/populateemployee/employeeusername当手动导航到 ..domain../staffinformation/populateemployee/employeeusername

I get the error我得到错误

This XML file does not appear to have any style information associated with it. The         
document tree is shown below.
<Error>
   <Message>
      The requested resource does not support http method 'GET'.
   </Message>
</Error>

Please note that the div it will be populating is a partial view in an Umbraco CMS page and I don't think that is the problem but if you guys think differently please tell me.请注意,它将填充的 div 是 Umbraco CMS 页面中的部分视图,我认为这不是问题,但如果你们有不同的想法,请告诉我。

There has to be something I am missing either with webAPI routing or something else. webAPI路由或其他东西我必须缺少一些东西。

Thanks for your help.谢谢你的帮助。

Here's the codez.这是代码。

Please notice that this method has the HttpPost tag请注意这个方法有 HttpPost 标签

public class StaffInformationController : ApiController
{    
    [System.Web.Http.ActionName("PopulateEmployee")]
    [System.Web.Http.HttpPost]
    public StaffListing PopulateEmployee(string id)
    {
        //do error checking on input
        StaffListing staffListing = new StaffListing(id);
        //populate other fields
        return staffListing;
    }
}

The routing set up for the api controller为 api 控制器设置的路由

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

The jQuery call specifying use of 'POST', please forgive the trickiness of the recursive call in this function.指定使用 'POST' 的 jQuery 调用,请原谅此函数中递归调用的棘手之处。

function getEmployeeObjectByIndex() {
$.ajax({
    url: $('#root').val() + '/api/StaffInformation/PopulateEmployee',
    type: 'POST',
    async: true,
    contentType: 'application/json, charset=utf-8',
    data: JSON.stringify({ 'username': lines[i] }),
    success: function (staffObject) {
        if (!(staffObject.Name == undefined)) {
            buildHtmlStrings(staffObject);
        }
        i++;
        getEmployeeObjectByIndex(); //recursive call
    }
});
}

manually navigating to that address throws the error because, when manually navigating you are doing a GET (and your method only allows POST s).手动导航到该地址会引发错误,因为在手动导航时您正在执行GET (并且您的方法仅允许POST )。

You should fire up Fiddler and watch the ajax POST request and response to see how the server is responding / your request is being made您应该启动 Fiddler 并观察 ajax POST请求和响应,以查看服务器如何响应/您的请求正在发出

Jquery ------> web api jQuery ------> web api

Web API has one property ie CONTENT NEGOTIATION means you send any data and accept any data as you want. Web API 有一个属性,即内容协商意味着您可以根据需要发送任何数据并接受任何数据。

$.ajax({ $.ajax({

contentType: 'application/json, charset=utf-8',

// this is sending your data of datatype json to server, here you send any type of data // 这是将数据类型为 json 的数据发送到服务器,这里您发送任何类型的数据

accept: 'application/json',

//this is receiving/getting data form server to client... // SO HERE YOU GET JSON DATA AS YOU WANT only mention which data of datatype u want... //if you sending xml and you want json so only write accept as json it get automatically converted into your required datatype..by MediaTypeFormatter //这是从服务器接收/获取数据到客户端... //所以在这里您可以获取 JSON 数据,只要提及您想要的数据类型的数据... //如果您发送 xml 并且您想要 json 所以只写接受为 json 它会自动转换为您所需的数据类型..by MediaTypeFormatter

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM