繁体   English   中英

如何更改ASP.NET调用REST Web API的方式

[英]How to change the way REST Web API is called for ASP.NET

我的控制器当前看起来像:

[Jsonp filter] 
public class ProductController : Controller
{

     public Json GetProduct(string id)
     {
          Product x;
          //code
          return Json(x, JsonRequestBehavior.AllowGet);
     }
 }

我能够获得执行此操作的产品:api / product / getproduct / 5

但是,我希望能够像这样访问它:api / product / 5

我需要做些什么改变?

编辑:我实际上正在使用Jsonp,因为我需要从其他域调用此API并获取一个json对象。 使用ApiController可以做到吗? 否则,有没有一种方法无需切换到ApiController?

您将必须编辑webapiconfig(位于App_Start文件夹中)。

您将需要在其他路线之前添加类似的内容(以确保首先被捕获):

// Map Http Route takes in 3 parameters below
// param 1 is the name of the route.. This has nothing to do with class names or method names
// param 2 is the route itself.  Route parameters are denoted in curly braces {likethis}
// param 3 sets up defaults
config.Routes.MapHttpRoute("GetProductApi", "api/product/{id}",
    new {
        controller = "Product",      // the name of the controller class (without the Controller suffix)
        action = "GetProduct",       // the name of your method
        id = RouteParameter.Optional
    });

另外,您控制器的代码似乎不是API控制器。 无论如何,这是一个路由问题。 如果100%需要,您可以在常规路由配置中添加路由配置。

您上面的代码不是WebApi控制器,而是MVC控制器。 您的类需要继承自ApiController,例如:

public class ProductController : ApiController{
...

关于您的方法,我不确定为什么要使用Json作为返回类型,因为它是MediaFormatter配置中用来定义返回格式的一部分,因此不应在方法/功能级别上对其进行定义。 看起来正确的方法声明将类似于:

public Product GetProduct(string id)
{
   Product x; //probably you want initialize it like new Product();       
   return x;
}

更新JsonP

WebApi如前所述基于MediaFormatters。 为了使用JsonP,您需要使用适当的媒体格式化程序,但是有几种方法:

http://www.nuget.org/packages/WebApi.JsonP

如果您想阅读有关WebApi的JsonP格式器的更多信息,请参阅以下SO Post:

您的ProductController应该派生自ApiController而不是Controller

以@Dalorzo的答案为基础,如果/何时可以转换为APIController,并且可以使用WebAPI 2,则可以在方法上使用装饰器属性 ,这将更改路由,甚至更改用于该方法的HTTP动词...这真的很好,因为您需要了解的有关该API调用的所有信息都在函数签名处。 它非常健壮和直观,我强烈推荐它。

暂无
暂无

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

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