首页 > 解决方案 > 等效于 Javascript 的 C# API 端点

问题描述

我正在尝试将一些 Javascript 代码重写为 c#,但停留在 2 个问题上。

这是原始代码:

module.exports = () => {
    const app = express.Router();
    app.get('/', cors(), validUrl, (req, res, next) => {
        switch (req.query.responseType) {
    case 'blob':
        req.pipe(request(req.query.url).on('error', next)).pipe(res);
        break;
    case 'text':
    default:
        request({url: req.query.url, encoding: 'binary'}, (error, response, body) => {
            if (error) {
                return next(error);
            }
            res.send(
            `data:${response.headers['content-type']};base64,${Buffer.from(
                body,
                'binary'
            ).toString('base64')}`
        );
    });
    }
});

完整代码在这里:

https://github.com/niklasvh/html2canvas-proxy-nodejs/blob/master/server.js

这是我必须要做的:

public static class Html2CanvasProxy
{
    [FunctionName("Html2CanvasProxy")]
    public static async Task<string> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log)
    {
        IDictionary<string, string> queryParams = req.GetQueryParameterDictionary();
        queryParams.TryGetValue("url", out string url);
        queryParams.TryGetValue("responseType: ", out string responseType);

        using var client = new HttpClient();
        byte[] bytes;

        switch (responseType)
        {
            case "blob":
                // what to do if it's a "blob"?
                return "What is the equivalent of req.pipe(request(req.query.url).on('error', next)).pipe(res);";
            case "text":
                // what to do if it's "text"? - is this correct?
                bytes = await client.GetByteArrayAsync(url);
                return Convert.ToBase64String(bytes);
        }

        return "Error";
    }
}

我无法弄清楚这一行发生了什么:

req.pipe(request(req.query.url).on('error', next)).pipe(res);

以及如何将其转换为 c#

我也被困在返回类型应该是什么上?只是一个对象?

标签: javascriptc#node.js

解决方案


推荐阅读