主机C#休息服务 - 返回类型

时间:2017-06-04 00:26:23

标签: c# rest

我正在尝试托管我在 c#中创建的休息服务,部署 .dll 文件并将其导入主要方法的新项目。

要在main中创建一个主机我为我的Rest服务创建了一个接口,但是在声明这个接口后我一直收到错误

  

"内容在当前上下文中不存在"

。内容是我的方法的回报,应仅返回无效任务任务T> ,因为异步方法。 我该如何解决这个错误?

这是 控制器 (休息服务)的一部分:

    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Net;
    using System.Net.Http.Headers;
    using System.Security.Cryptography;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Http;
    using System.ServiceModel;
    using Couchbase;
    using Couchbase.Core;
    using Couchbase.IO;
    using JWT;



    [ServiceContract]
    public interface ApiController
    {
        Task<IHttpActionResult> SignUp(LoginModel model);
    }

    namespace Nerder_Backend.Controllers
    {
        [RoutePrefix("api/user")]
        public class UserController : ApiController
        {
            private readonly IBucket _bucket = ClusterHelper.GetBucket(ConfigurationManager.AppSettings.Get("CouchbaseUserBucket"));
            private readonly string _secretKey = ConfigurationManager.AppSettings["JWTTokenSecret"];

            [Route("signup")]
            [HttpPost]
            public async Task<IHttpActionResult> SignUp(LoginModel model)
            {
                if (model == null || !model.IsValid())
                {
                    return Content(HttpStatusCode.BadRequest, new Error("Invalid email and/or password"));
                }

 var userKey = CreateUserKey(model.Email);
            if (await _bucket.ExistsAsync(userKey))
            {
                return Content(HttpStatusCode.Conflict, new Error($"email '{model.Email}' already exists"));
            }

            var userDoc = new Document<User>
            {
                Id = userKey,
                Content = new User
                {
                    Email = model.Email,
                    Password = CalcuateMd5Hash(model.Password)
                },
                Expiry = model.Expiry
            };

            var result = await _bucket.InsertAsync(userDoc);
            if (!result.Success)
            {
                return Content(HttpStatusCode.InternalServerError, new Error(result.Message));
            }

            var data = new
            {
                token = BuildToken(model.Email)
            };
            var context = $"Created user with ID '{userKey}' in bucket '{_bucket.Name}' that expires in {userDoc.Expiry}ms";
            return Content(HttpStatusCode.Accepted, new Result(data, context));
        }

这是 主要 方法:

namespace MockServer
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8080/signup");

            // Create the ServiceHost.
            using (ServiceHost host = new ServiceHost(typeof(UserController), baseAddress))
            {
                // Enable metadata publishing.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);

                // Open the ServiceHost to start listening for messages. Since
                // no endpoints are explicitly configured, the runtime will create
                // one endpoint per base address for each service contract implemented
                // by the service.
                host.Open();

                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                // Close the ServiceHost.
                host.Close();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

更新main以正确托管网络API。

包括以下使用陈述

using System.Web.Http;
using System.Web.Http.SelfHost; //install the nuget package Microsoft.AspNet.WebApi.SelfHost

更新Program类以托管Web API

class Program {
    static void Main(string[] args) {
        var baseAddress = "http://localhost:8080";
        var config = new HttpSelfHostConfiguration(baseAddress);
        config.MapHttpAttributeRoutes();//map attribute routes
        // Create the server
        using (var server = new HttpSelfHostServer(config)) {
            server.OpenAsync().Wait();
            Console.WriteLine("The service is ready at {0}", baseAddress);
            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();
        }
    }
}

现在确保api控制器正确定义。

[RoutePrefix("api/user")]
public class UserController : ApiController {
    private readonly IBucket _bucket = ClusterHelper.GetBucket(ConfigurationManager.AppSettings.Get("CouchbaseUserBucket"));
    private readonly string _secretKey = ConfigurationManager.AppSettings["JWTTokenSecret"];
    [HttpPost]
    [Route("signup")] //Matches POST api/user/signup
    public async Task<IHttpActionResult> SignUp(LoginModel model) {

        //...code removed for brevity

    }
}

给定程序集和控制器属性路由,可以在

找到该动作
POST http://localhost:8080/api/user/signup