Skip to main content
 首页 » 编程设计

c#之WebApi 2 GET 在参数中有特殊字符

2024年05月06日40shihaiming

当我使用具有特殊字符 的字符串参数调用 webapi2 GET 时,我的问题就来了(正常字符都可以正常工作)。

AngularJs

this.getByContactValue = function (contactValue) {    
        return $http.get("/api/subjects/"+ contactValue+ "/ContactValue" ); 
    } 

c#

[Route("api/subjects/{contactValue}/ContactValue")] 
public IEnumerable<Subject> GetByContactValue(string contactValue) 
{ 
    return repository.GetByContactValue(contactValue); 
} 

响应是404 错误。 我也试过这样修改请求

this.getByContactValue = function (contactValue) { 
        var request = $http({ 
            method: "get", 
            url: "/api/subjects/ContactValue", //modified the route in c# controller 
            data: contactValue 
        }); 
        return request; 
    } 

但错误是一样的。

调用 webapi 的最佳方式是什么?

请您参考如下方法:

您必须将查询字符串中的数据作为

$http({ 
    url: "/api/subjects/ContactValue",  
    method: "GET", 
    params: {contactValue: contactValue} 
 }); 

更新你的 Action

[Route("api/subjects/ContactValue?contactValue={contactValue}")] 
public IEnumerable<Subject> GetByContactValue(string contactValue) 
{ 
    return repository.GetByContactValue(contactValue); 
}