标签: asp.net-web-api

无法将列表转换为Json

我有以下操作方法:

public class MyDeviceController : ApiController
{
    // GET api/<controller>
    public JsonResult Get()
    {
        int userId = -1;
        List<String> myDevices1 = new List<String>();
        myDevices1.Add("1");
        >> return Json(myDevices1); << Error here           
    }
}
Run Code Online (Sandbox Code Playgroud)

返回带有下划线红色,并显示以下错误:

cannot implicitly convert type (JsonResult to List<string>)
Run Code Online (Sandbox Code Playgroud)

我正在使用Asp.net Web Api.我认为它在使用System.web.http和System.mvc.http h之间感到困惑

c# asp.net-mvc json asp.net-web-api

0
推荐指数
1
解决办法
2713
查看次数

返回HttpResponseMessage的方法 - 如何返回Exception,这可能吗?

我正在使用ASP.NET WebAPI2.这是我的代码:

[HttpPost]
    public HttpResponseMessage SaveNewPdf(HttpRequestMessage req)
            {
                var json = req.Content.ReadAsStringAsync().Result;
                NewFile newFile = JsonConvert.DeserializeObject<NewFile>(json);
                string error = string.Empty;

                // check all the foreign key values to ensure they are valid
                var isArticleCategoryValid = HelperClasses.ForeignKeyChecks.IsArticleCategoryValid(newFile.ArticleCategory);
                var isDocumentTypeValid = HelperClasses.ForeignKeyChecks.IsDocumentTypeValid(newFile.DocumentType);
                var isActionPublisherValid = HelperClasses.ForeignKeyChecks.IsActionPublisherValid(newFile.ActionPublisher);
                var isRuleComplianceValid = HelperClasses.ForeignKeyChecks.IsRuleComplianceValid(newFile.RuleCompliance);

                if (!isArticleCategoryValid)
                {
                    error = "articleCategory in the JSON is not a valid Article Category";
                    return new HttpResponseException();
                }
    }
Run Code Online (Sandbox Code Playgroud)

我想做一些如上所示的事情 - 返回一个表示错误的异常.我知道我可以返回一个HttpResponseMessage,其状态代码是我想要的,但我想返回一个Exception.我知道HttpResponseException,但这需要一个HttpResponseMessage,所以我回到原点.可能会返回异常吗?

c# exception http httpresponse asp.net-web-api

0
推荐指数
1
解决办法
248
查看次数

如何在vb.net中使用HttpClient读取JSON响应

我已经构建了一个用于访问WEB API服务的java例程,但是我正在为ASP.Net的VB等价物而苦苦挣扎.我得到API响应,但我不知道如何将其转换为json元素.

java版本是:

    public boolean canLogin(){
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(hostURL + TOKEN_ACCESS_URL);
    httppost.addHeader("Accept", "application/json");

    // Add the post content
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
    nameValuePairs.add(new BasicNameValuePair("grant_type", "password"));
    nameValuePairs.add(new BasicNameValuePair("username", accessUserName));
    nameValuePairs.add(new BasicNameValuePair("password", accessPassword));
    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e1) {
        mobileLogDataHandler.ToLog(LogType.Error, "UnsupportedEncodingException closing data stream with error: " + e1.getLocalizedMessage() + ",detail:" + e1.getMessage() + " in canLogin", mResolver, RemoteDataHandler.class);
        return false;
    }

    // post the server
    InputStream inputStream = null;
    String …
Run Code Online (Sandbox Code Playgroud)

vb.net asp.net-web-api dotnet-httpclient

0
推荐指数
1
解决办法
1万
查看次数

我可以在ASP.NET Web Forms 4.5中使用WebAPi的完整功能吗?

我想创建一些Web服务,但我决定使用WebAPI作为服务框架而不是WCF,所以我有一些问题:

  1. 我可以使用全功能的WebAPI的ASP.NET Web窗体 4.5 没有任何问题

  2. WebForms 4.5与异步等待编程一起使用?

  3. WebForms 4.5可以与HttpClient库和异步编程一起使用, 没有任何问题或限制吗?

  4. 有没有什么特别的限制,的WebAPIASP.NET的WebForms 4.5?(反之亦然)

*如果有限制,我将被迫使用WCF :(

c# asp.net webforms async-await asp.net-web-api

0
推荐指数
1
解决办法
115
查看次数

如何将Web API 2 HttpRequestMessage序列化到我的自定义对象中

我的WebAPI 2项目中有以下方法.

public class TestController : ApiController
{
    [HttpPost]
    public void Test(HttpRequestMessage request)
    {
        var content = request.Content;
        string jsonContent = content.ReadAsStringAsync().Result;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的自定义对象看起来像这样;

public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如果我发布一些样本数据,如

<Test>
    <Id>12345</Id>
    <Name>My Name</Name>
</Test>
Run Code Online (Sandbox Code Playgroud)

jsonContent中的结果值是正确的.我的问题是我应该如何最好地将HttpRequestMessage(内容)序列化到我的对象Test中,以便我可以执行其他验证/任务等.

我应该将HttpRequestMessage传递给方法还是可以传递类似的东西

public void Test(Test oTest)
Run Code Online (Sandbox Code Playgroud)

c# asp.net-web-api

0
推荐指数
1
解决办法
4192
查看次数

使用Dot Net核心实现缓存管理器

我是DotNet Core的新手.我使用.NEt Core创建了一个WEB API.我需要在此API中实现缓存管理器.我有一组记录会在一天内更新一次,因此我希望这些数据存储在内存中的对象中,并且只有在检测到更改时(或者以一定的间隔,比如3小时)才调用数据库.我已经尝试在我的应用程序中实现逻辑.但是想知道我们是否已经有特定的包装!

请帮我.

提前致谢.

c# caching asp.net-web-api .net-core asp.net-core

0
推荐指数
1
解决办法
2940
查看次数

ASP.NET MVC URI参数命名

我正在使用ASP.NET MVC Web Api控制器,我只是一个初学者,所以也许我的问题非常简单......

我想将一个名为$filterinput 的参数作为控制器的方法:

[Route("List")]
[HttpGet]
public IHttpActionResult List([FromUri] string $filter = null)
{
    // ... code here ...

    return (Ok());
}
Run Code Online (Sandbox Code Playgroud)

但是我不能这样做,因为$filter它不是一个有效的C#变量名!

无论如何(由于客户的要求)我真的需要调用传递$filter=somethingURI的方法...

我能怎么做?有没有一种方法可以"映射"URI参数的命名,这样在代码中我可以使用变量名filter(没有美元),然后指示MVC层映射$filterfilter

c# asp.net asp.net-mvc asp.net-web-api

0
推荐指数
1
解决办法
299
查看次数

获取响应为"data":null,"status": - 从AngularJS调用web api时为1

我试图从Angular JS 1.6.0调用Web API GET方法并得到以下错误: -

可能未处理的拒绝:{"data":null,"status": - 1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam" :"callback","url":" http:// localhost:51972/api/video ","headers":{"Accept":"application/json,text/plain,/ "}},"statusText": ""}

当我从Fiddler 4调用相同的GET方法并返回JSON Text时,我得到了正确的JSON响应.

请注意,我的WEB API和Angular JS代码位于不同的目录中.

根据Dez的评论,我修改了WebApiConfig.cs以从WebAPI返回JSON响应

WebApiConfig.cs

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }
    }
Run Code Online (Sandbox Code Playgroud)

VideoController.cs

public class VideoController : ApiController
{
        [Route("api/video")]
        public List<VideoViewModel> GetVideo()
        {
            List<VideoViewModel> video = new List<VideoViewModel>();
            video.Add(new VideoViewModel { Name = …
Run Code Online (Sandbox Code Playgroud)

asp.net-web-api angularjs angularjs-http

0
推荐指数
1
解决办法
5678
查看次数

客户端证书和证书固定之间的区别,我是否需要两者?

我有一个公开公开的.net WEB API,还有一个使用该API的Xamarin Forms应用程序,该应用程序由于要管理的数据而需要非常安全。

我将为WEB API创建一个HTTP证书。Xamarin Forms应用程序将具有登录名/密码,以针对本地Active Directory进行验证。通过一个/ token端点,并在所有端点上使用Authorize属性来确保每个HTTP调用中都包含不记名令牌,我使用以下方法实现了这一点:

我基于此实现:http : //bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

另外,客户要求我们提供客户证书认证,我不知道这是如何工作的。1.我需要向Xamarin项目添加证书,对吗?如何添加?我如何产生它?2.在Web API中,我需要验证每个http调用是否都附加了证书。我发现了这一点,但不确定是否会起作用:http : //www.razibinrais.com/secure-web-api-with-client-certificate/

但是,在调查此问题时,我还发现了有关证书固定的问题,这本质上是安全性,但反过来说,这意味着Xamarin APP将验证服务器证书是否与正确的服务器(或类似的服务器)相关联,因此没有人可以在中间进攻。我在这里找到了实施方法:https//thomasbandt.com/certificate-and-public-key-pinning-with-xamarin

问题是:1.我两个都需要吗?

在此过程中,我还需要研究什么?

security ssl ssl-certificate asp.net-web-api xamarin

0
推荐指数
1
解决办法
837
查看次数

"尝试创建'HomeController'类型的控制器时发生错误.确保控制器具有无参数的公共构造函数

我是建筑师的新手.请解释为什么它给我以下错误:

"An error occurred when trying to create a controller of type 'HomeController'. Make sure that the controller has a parameterless public constructor.
Run Code Online (Sandbox Code Playgroud)

这里我有1个接口(IRepo)1类文件(Repo)IRepo.cs

public interface IRepo
    {
        IEnumerable<Employee> GetEmployee();
        IQueryable<Employee> GetEmployee(int id);
    }
Run Code Online (Sandbox Code Playgroud)

Repo.cs

Ctxdb _db = null;
        public Repo(Ctxdb db)
        {
            this._db = db;
        }

        public IEnumerable<Employee> GetEmployee()
        {
           //  
        }
Run Code Online (Sandbox Code Playgroud)

HomeController.cs

IRepo _ObjRepo = null;

        public HomeController(Repo ObjRepo)
        {

            _ObjRepo = ObjRepo;
        }

        [Route("GetEmp")]
        [HttpGet]
        public IHttpActionResult GetDat()
        {
            var x = _ObjRepo.GetEmployee();
            if (x != null) …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-web-api

0
推荐指数
1
解决办法
4769
查看次数